package com.example.smartg;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
//import android.view.Menu;
//import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.smartg.utils.LogoutDialogUtil;
import com.example.smartg.utils.ToastUtil;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.core.utils.ToolUtils;
import com.zkteco.android.biometric.module.fingerprintreader.FingerprintCaptureListener;
import com.zkteco.android.biometric.module.fingerprintreader.FingerprintSensor;
import com.zkteco.android.biometric.module.fingerprintreader.FingprintFactory;
import com.zkteco.android.biometric.module.fingerprintreader.ZKFingerService;
import com.zkteco.android.biometric.module.fingerprintreader.exception.FingerprintException;


//import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.FileOutputStream;
//import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import okhttp3.Call;
import okhttp3.Response;


public class Login extends AppCompatActivity {
    private static final int VID = 6997;
    private static final int PID = 288;
    private ImageView imageView = null;
//    private boolean isRegister = true;

    private byte[][] regtemparray = new byte[3][2048];  //register template buffer array
    private int enrollidx = 0;
    private byte[] lastRegTemp = new byte[2048];
    //    private boolean bstart = false;
    //    private int uid = 1;
    //    String result = "";

    private FingerprintSensor fingerprintSensor = null;

    private final String ACTION_USB_PERMISSION = "com.example.smartg.USB_PERMISSION";

    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns

    private void initUSBPermission() {
        UsbManager usbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
        for (UsbDevice device : usbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                usbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    // 记录上一次操作时间
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // #start 管理员通用模块
        TextView textViewUsername = (TextView) findViewById(R.id.user_name);
        String user_name = SpUtils.getString(this, "user_name", "未登录");
        textViewUsername.setText(user_name);
        textViewUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogoutDialogUtil.logout(Login.this);
            }
        });
        ImageView home_logo = (ImageView) findViewById(R.id.home_logo);
        home_logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // #end 管理员通用模块

        imageView = (ImageView) findViewById(R.id.finger_print);
        startFingerprintSensor();
        initUSBPermission();
        beginFinger();

        // 加上计时器
        startTimer();
    }

    public void beginFinger() {
        try {
            fingerprintSensor.open(0);
            final FingerprintCaptureListener listener = new FingerprintCaptureListener() {
                @Override
                public void captureOK(final byte[] fpImage) {
                    final int width = fingerprintSensor.getImageWidth();
                    final int height = fingerprintSensor.getImageHeight();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (null != fpImage) {
                                ToolUtils.outputHexString(fpImage);
                                LogHelper.i("width=" + width + "\nHeight=" + height);
                                Bitmap bitmapFp = ToolUtils.renderCroppedGreyScaleBitmap(fpImage, width, height);
                                //saveBitmap(bitmapFp);
                                imageView.setImageBitmap(bitmapFp);
                            }
                            //Log.e("error","FakeStatus:" + fingerprintSensor.getFakeStatus());
                        }
                    });
                }

                @Override
                public void captureError(FingerprintException e) {
                }

                @Override
                public void extractError(final int err) {
                    Log.e("extractError", Integer.toString(err));
                }

                @Override
                public void extractOK(final byte[] fpTemplate) {
                    final byte[] tmpBuffer = fpTemplate;
                    final int templateLen = fingerprintSensor.getLastTempLen();
                    Log.e("extractOK", Integer.toString(templateLen));
                    //Base64 Template
                    //String strBase64 = Base64.encodeToString(tmpBuffer, 0, templateLen, Base64.NO_WRAP);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            byte[] bufids = new byte[256];
                            ZKFingerService.clear();
                            int ret = ZKFingerService.identify(tmpBuffer, bufids, 55, 1);
                            if (ret > 0) {
                                String strRes[] = new String(bufids).split("\t");
//                                    textView.setText("the finger already enroll by " + strRes[0] + ",cancel enroll");
                                ToastUtil.error(Login.this, "不同人，请重新开始！");
                                enrollidx = 0;
                                return;
                            }

                            if (enrollidx > 0 && ZKFingerService.verify(regtemparray[enrollidx - 1], tmpBuffer) <= 0) {
                                ToastUtil.error(Login.this, "请重新按压！");
                                return;
                            }
                            System.arraycopy(tmpBuffer, 0, regtemparray[enrollidx], 0, 2048);
                            enrollidx++;
                            if (enrollidx == 3) {
                                byte[] regTemp = new byte[2048];
                                if (0 < (ret = ZKFingerService.merge(regtemparray[0], regtemparray[1], regtemparray[2], regTemp))) {
//                                    ZKFingerService.save(regTemp, "郑楚鑫");
                                    System.arraycopy(regTemp, 0, lastRegTemp, 0, ret);
                                    //Base64 Template
                                    String strBase64 = Base64.encodeToString(regTemp, 0, ret, Base64.NO_WRAP);
                                    Log.e("strBase64", strBase64);
//                                        textView.setText("enroll succ, uid:" + uid + "count:" + ZKFingerService.count());
//                                    ToastUtil.success(Login.this, "更新成功！");
                                    // 发往服务器
                                    update_fingerprint(strBase64);
                                } else {
//                                        textView.setText("enroll fail");
                                    ToastUtil.error(Login.this, "更新失败！");
                                }
                                enrollidx = 0;
                            } else {
//                                    textView.setText("You need to press the " + (3 - enrollidx) + "time fingerprint");
                                ToastUtil.success(Login.this, "还需按压" + +(3 - enrollidx) + "次！");
                            }
//                            if (isRegister) {
//
//                            } else {

//                                 测试
//                                ZKFingerService.clear();
//                                Log.e("count", Integer.toString(ZKFingerService.count()));
//                                Log.e("长度", result);
//                                byte[] regTemp = Base64.decode(result, Base64.NO_WRAP);
//                                Log.e("le", Integer.toString(regTemp.length));
//                                ZKFingerService.save(regTemp, "郑楚鑫");
//                                Log.e("count2", Integer.toString(ZKFingerService.count()));
////                                old
//                                byte[] bufids = new byte[256];
//                                int ret = ZKFingerService.identify(tmpBuffer, bufids, 70, 1);
//                                if (ret > 0) {
//                                    String strRes[] = new String(bufids).split("\t");
//                                    textView.setText("identify succ, userid:" + strRes[0] + ", score:" + strRes[1]);
//                                } else {
//                                    textView.setText("identify fail");
//                                }
//                            }
                        }
                    });
                }


            };
            fingerprintSensor.setFingerprintCaptureListener(0, listener);
            fingerprintSensor.startCapture(0);
            Log.e("open", "start capture succ");
            ToastUtil.success(Login.this, "成功打开指纹识别器！");
        } catch (FingerprintException e) {
            Log.e("open", "start capture unsucc");
        }
    }

    private void startFingerprintSensor() {
        // Define output log level
        LogHelper.setLevel(Log.ASSERT);
        LogHelper.setNDKLogLevel(Log.ASSERT);
        // Start fingerprint sensor
        Map fingerprintParams = new HashMap();
        //set vid
        fingerprintParams.put(ParameterHelper.PARAM_KEY_VID, VID);
        //set pid
        fingerprintParams.put(ParameterHelper.PARAM_KEY_PID, PID);
        fingerprintSensor = FingprintFactory.createFingerprintSensor(this, TransportType.USB, fingerprintParams);
    }


//    public void OnBnBegin() {
//        try {
//            if (bstart) return;
//            fingerprintSensor.open(0);
//            final FingerprintCaptureListener listener = new FingerprintCaptureListener() {
//                @Override
//                public void captureOK(final byte[] fpImage) {
//                    final int width = fingerprintSensor.getImageWidth();
//                    final int height = fingerprintSensor.getImageHeight();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (null != fpImage) {
//                                ToolUtils.outputHexString(fpImage);
//                                LogHelper.i("width=" + width + "\nHeight=" + height);
//                                Bitmap bitmapFp = ToolUtils.renderCroppedGreyScaleBitmap(fpImage, width, height);
//                                //saveBitmap(bitmapFp);
//                                imageView.setImageBitmap(bitmapFp);
//                            }
//                            //textView.setText("FakeStatus:" + fingerprintSensor.getFakeStatus());
//                        }
//                    });
//                }
//
//                @Override
//                public void captureError(FingerprintException e) {
//                    final FingerprintException exp = e;
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            LogHelper.d("captureError  errno=" + exp.getErrorCode() +
//                                    ",Internal error code: " + exp.getInternalErrorCode() + ",message=" + exp.getMessage());
//                        }
//                    });
//                }
//
//                @Override
//                public void extractError(final int err) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            textView.setText("extract fail, errorcode:" + err);
//                        }
//                    });
//                }
//
//                @Override
//                public void extractOK(final byte[] fpTemplate) {
//                    final byte[] tmpBuffer = fpTemplate;
//                    final int templateLen = fingerprintSensor.getLastTempLen();
//                    Log.e("extractOK", Integer.toString(templateLen));
//                    //Base64 Template
//                    //String strBase64 = Base64.encodeToString(tmpBuffer, 0, templateLen, Base64.NO_WRAP);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (isRegister) {
//                                byte[] bufids = new byte[256];
//                                int ret = ZKFingerService.identify(tmpBuffer, bufids, 55, 1);
//                                if (ret > 0) {
//                                    String strRes[] = new String(bufids).split("\t");
//                                    textView.setText("the finger already enroll by " + strRes[0] + ",cancel enroll");
//                                    isRegister = false;
//                                    enrollidx = 0;
//                                    return;
//                                }
//
//                                if (enrollidx > 0 && ZKFingerService.verify(regtemparray[enrollidx - 1], tmpBuffer) <= 0) {
//                                    textView.setText("please press the same finger 3 times for the enrollment");
//                                    return;
//                                }
//                                System.arraycopy(tmpBuffer, 0, regtemparray[enrollidx], 0, 2048);
//                                enrollidx++;
//                                if (enrollidx == 3) {
//                                    byte[] regTemp = new byte[2048];
//                                    if (0 < (ret = ZKFingerService.merge(regtemparray[0], regtemparray[1], regtemparray[2], regTemp))) {
//                                        ZKFingerService.save(regTemp, "郑楚鑫");
//                                        System.arraycopy(regTemp, 0, lastRegTemp, 0, ret);
//                                        //Base64 Template
//                                        String strBase64 = Base64.encodeToString(regTemp, 0, ret, Base64.NO_WRAP);
//                                        result = strBase64;
//                                        textView.setText("enroll succ, uid:" + uid + "count:" + ZKFingerService.count());
//                                    } else {
//                                        textView.setText("enroll fail");
//                                    }
//                                    isRegister = false;
//                                } else {
//                                    textView.setText("You need to press the " + (3 - enrollidx) + "time fingerprint");
//                                }
//                            } else {
//
////                                 认证的时候使用
////                                ZKFingerService.clear();
////                                Log.e("count", Integer.toString(ZKFingerService.count()));
////                                Log.e("长度", result);
////                                byte[] regTemp = Base64.decode(result, Base64.NO_WRAP);
////                                Log.e("le", Integer.toString(regTemp.length));
////                                ZKFingerService.save(regTemp, "郑楚鑫");
////                                Log.e("count2", Integer.toString(ZKFingerService.count()));
//////                                old
////                                byte[] bufids = new byte[256];
////                                int ret = ZKFingerService.identify(tmpBuffer, bufids, 70, 1);
////                                if (ret > 0) {
////                                    String strRes[] = new String(bufids).split("\t");
////                                    textView.setText("identify succ, userid:" + strRes[0] + ", score:" + strRes[1]);
////                                } else {
////                                    textView.setText("identify fail");
////                                }
//                            }
//                        }
//                    });
//                }
//
//
//            };
//            fingerprintSensor.setFingerprintCaptureListener(0, listener);
//            fingerprintSensor.startCapture(0);
//            bstart = true;
//            textView.setText("start capture succ");
//            Log.e("open", "start capture succ");
//        } catch (FingerprintException e) {
////            textView.setText("begin capture fail.errorcode:" + e.getErrorCode() + "err message:" + e.getMessage() + "inner code:" + e.getInternalErrorCode());
//              ToastUtil.error(Login.this,"指纹识别器初始化失败！");
//        }
//    }
//
//    public void OnBnStop(View view) throws FingerprintException {
//        try {
//            if (bstart) {
//                //stop capture
//                fingerprintSensor.stopCapture(0);
//                bstart = false;
//                fingerprintSensor.close(0);
////                textView.setText("stop capture succ");
//                ToastUtil.success(Login.this, "成功断开指纹识别器！");
////                Log.e("info:","stop capture succ");
//            } else {
////                textView.setText("already stop");
//                ToastUtil.success(Login.this, "指纹识别器已经断开！");
////                System.out.print("already stop");
////                Log.e("info:","already stop");
//            }
//        } catch (FingerprintException e) {
////            textView.setText("stop fail, errno=" + e.getErrorCode() + "\nmessage=" + e.getMessage());
//            Log.e("info:","stop fail, errno=" + e.getErrorCode() + "\nmessage=" + e.getMessage());
//        }
//
//    }
//
//    public void OnBnEnroll(View view) {
//        if (bstart) {
//            isRegister = true;
//            enrollidx = 0;
////            textView.setText("You need to press the 3 time fingerprint");
//        } else {
////            textView.setText("please begin capture first");
//        }
//    }
//
//    public void OnBnVerify(View view) {
//        if (bstart) {
//            isRegister = false;
//            enrollidx = 0;
//        } else {
////            textView.setText("please begin capture first");
//        }
//    }

    public void stopFinger() {
        try {
            //stop capture
            fingerprintSensor.stopCapture(0);
            fingerprintSensor.close(0);
            Log.e("OnBnStop", "success");
//            ToastUtil.success(Login.this, "成功断开指纹识别器！");

        } catch (FingerprintException e) {
            Log.e("OnBnStop", e.toString());
        }

    }


    @Override
    protected void onDestroy() {
        stopFinger();
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
        stopFinger();
    }

    public void update_fingerprint(String fingerprint) {
        //查询申请人存柜情况
        String url = "http://10.2.47.115/smartg_api/fingerprint_manage/fingerprint_entry";
        //实例化
        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("fingerprint", fingerprint);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("exception", e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(Login.this, "访问出错！");
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.success(Login.this, "更新成功！");
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.error(Login.this, msg);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 1分钟未操作停止计时并退出登录
            TextView tv = (TextView) findViewById(R.id.countdown3);
            long mLastActionTime = SpUtils.getLong(Login.this,"lastActionTime",0);
            if((System.currentTimeMillis() - mLastActionTime - 5000) / 1000 > 0){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText( 60 - (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "秒后退出！！");
                    }
                });
            }else{
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("");
                    }
                });
            }
            Log.e("=1=", (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "");
            if (System.currentTimeMillis() - mLastActionTime - 5000 > 1000 * 60 * 1) {
                stopTimer();
                SpUtils.clear(Login.this);
                finish();
            }

        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=1=", "主页定时任务启动");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");

    }

}



